const axios = require('axios')
const https = require('https');

const ppy_cfg      = require('./ppy_xterm.json');
const {ppy_pty}    = require('./ppy_pty');
const {ppy_ssh}    = require('./ppy_ssh');
const {ppy_docker} = require('./ppy_docker');

const axios_ignore_ssl = axios.create({
    baseURL: ppy_cfg.authapi_url, 
    httpsAgent: new https.Agent({
        rejectUnauthorized: false
    })
});

async function ssh_task(ctx){
    if(ctx.query.asset_id == null){
        ctx.websocket.send('asset_id参数缺失::连接关闭.\n\r');
        return;
    } 
    console.log(`asset_id:${ctx.query.asset_id}`);

    let res = null;
    try {
        res = await axios_ignore_ssl({
            method: 'get',
            url: '/authapi', // 请求的路径
            params: { // get参数会将请求参数拼接在url上
                asset_id: ctx.query.asset_id
            }, 
            data: {}, // post会将请求参数放在请求体中
            headers: {}, // 设置请求头，例如设置token等
            timeout: 500 // 设置请求超时时长，单位：ms
        });
    } catch (error) {
        //console.log(error)
        console.log('axios_ignore_ssl error');
        ctx.websocket.send('认证失败=-1::连接关闭.\n\r');
        return;
    }
    
    if(res == null){
        ctx.websocket.send('认证失败=-2::连接关闭.\n\r');
        return;
    }
    
    console.log(res.data);
    const error_code = res.data.error_code; 
    if(res.data.error_code != 0){
        ctx.websocket.send(`认证失败::错误码=${error_code}::连接关闭.\n\r`);
        return;
    } 
    
    ctx.websocket.send('认证成功\n\r');
    ctx.state.opts = res.data;
    if(res.data.host_type == 'ssh'){
        await ppy_ssh(ctx);
    }
}

async function pty_task(ctx){
    if(ctx.query.asset_id != ppy_cfg.pty_token){
        ctx.websocket.send('Token错误.\n\r');
        return;
    }
    await ppy_pty(ctx);
}

async function docker_task(ctx){
    if(ctx.query.container_id == null){
        ctx.websocket.send('参数错误.\n\r');
        return;
    }
    await ppy_docker(ctx);
}

const ppy_ws = async (ctx) => {
    ctx.websocket.send('\n\r连接中::');
    
    if(ctx.query.type == null){
        ctx.websocket.send('类型缺失::连接关闭.\n\r');
        return;
    }
    
    if(ctx.query.type == 'pty') await pty_task(ctx);
    else if(ctx.query.type == 'ssh') await ssh_task(ctx);
    else if(ctx.query.type == 'docker') await docker_task(ctx);
    else ctx.websocket.send('参数错误::连接关闭.\n\r');
}

module.exports = {
    ppy_ws
}
